import express from 'express';
import { createServer } from 'http';
import cors from 'cors';
import path from 'path';
import { fileURLToPath } from 'url';

// 导入自定义模块
import { config, updateAnnouncedIp } from './config.js';
import { MediaManager } from './mediaManager.js';
import { StreamManager } from './streamManager.js';
import { SignalingServer } from './signaling.js';

// ES模块中获取 __dirname
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

class MediasoupRTSPServer {
  constructor() {
    this.app = express();
    this.httpServer = null;
    this.mediaManager = null;
    this.streamManager = null;
    this.signalingServer = null;
  }

  async initialize() {
    try {
      console.log('🚀 Starting Mediasoup RTSP Server...');
      
      // 更新配置中的 IP 地址
      updateAnnouncedIp();
      
      // 初始化 Express 应用
      this.setupExpress();
      
      // 创建 HTTP 服务器
      this.createHttpServer();
      
      // 初始化 MediaManager
      await this.initializeMediaManager();

      // 初始化 Stream Manager
      this.initializeStreamManager();

      // 初始化信令服务器
      this.initializeSignalingServer();
      
      // 启动服务器
      this.startServer();
      
      console.log('✅ Mediasoup RTSP Server started successfully!');
      
    } catch (error) {
      console.error('❌ Failed to start server:', error);
      process.exit(1);
    }
  }

  setupExpress() {
    console.log('Setting up Express application...');
    
    // 中间件
    this.app.use(cors());
    this.app.use(express.json());
    this.app.use(express.urlencoded({ extended: true }));
    
    // 静态文件服务 (为前端提供服务)
    const publicPath = path.join(__dirname, '../public');
    this.app.use(express.static(publicPath));

    // 提供 mediasoup-client 库
    const mediasoupClientPath = path.join(__dirname, '../node_modules/mediasoup-client/lib');
    this.app.use('/mediasoup-client', express.static(mediasoupClientPath));
    
    // API 路由
    this.setupRoutes();
  }

  setupRoutes() {
    // 健康检查
    this.app.get('/api/health', (req, res) => {
      res.json({
        status: 'ok',
        timestamp: new Date().toISOString(),
        mediasoup: {
          worker: this.mediaManager?.getWorker()?.pid || null,
          router: this.mediaManager?.getRouter()?.id || null
        },
        rtsp: {
          active: this.rtspHandler?.isStreamActive() || false
        }
      });
    });

    // 获取 Router RTP Capabilities
    this.app.get('/api/rtp-capabilities', (req, res) => {
      try {
        const rtpCapabilities = this.mediaManager.getRouterRtpCapabilities();
        res.json({ rtpCapabilities });
      } catch (error) {
        res.status(500).json({ error: error.message });
      }
    });

    // 启动 RTSP 流
    this.app.post('/api/rtsp/start', async (req, res) => {
      try {
        const { rtspUrl } = req.body;
        
        if (!rtspUrl) {
          return res.status(400).json({ error: 'RTSP URL is required' });
        }

        const result = await this.rtspHandler.startStream(rtspUrl);
        res.json(result);
        
      } catch (error) {
        console.error('Error starting RTSP stream:', error);
        res.status(500).json({ error: error.message });
      }
    });

    // 停止 RTSP 流
    this.app.post('/api/rtsp/stop', async (req, res) => {
      try {
        await this.rtspHandler.stopStream();
        res.json({ success: true, message: 'RTSP stream stopped' });
        
      } catch (error) {
        console.error('Error stopping RTSP stream:', error);
        res.status(500).json({ error: error.message });
      }
    });

    // 获取 RTSP 流状态
    this.app.get('/api/rtsp/status', (req, res) => {
      try {
        const producers = this.rtspHandler.getProducers();
        res.json({
          active: this.rtspHandler.isStreamActive(),
          producers: {
            video: producers.video?.id || null,
            audio: producers.audio?.id || null
          }
        });
      } catch (error) {
        res.status(500).json({ error: error.message });
      }
    });

    // 获取统计信息
    this.app.get('/api/stats', async (req, res) => {
      try {
        const stats = await this.mediaManager.getStats();
        res.json(stats);
      } catch (error) {
        res.status(500).json({ error: error.message });
      }
    });

    // 默认路由 - 返回前端应用
    this.app.get('/', (req, res) => {
      res.sendFile(path.join(__dirname, '../index.html'));
    });
  }

  createHttpServer() {
    console.log('Creating HTTP server...');
    this.httpServer = createServer(this.app);
  }

  async initializeMediaManager() {
    console.log('Initializing MediaManager...');
    this.mediaManager = new MediaManager(config);
    await this.mediaManager.initialize();
  }

  initializeStreamManager() {
    console.log('Initializing Stream Manager...');
    this.streamManager = new StreamManager(
      this.mediaManager.getRouter(),
      config
    );

    // 监听流管理器事件
    this.streamManager.on('streamStarted', (data) => {
      console.log('Stream started:', data);
    });

    this.streamManager.on('streamStopped', (data) => {
      console.log('Stream stopped:', data);
    });
  }

  initializeSignalingServer() {
    console.log('Initializing Signaling Server...');
    this.signalingServer = new SignalingServer(
      this.httpServer,
      this.mediaManager,
      this.streamManager,
      config
    );
  }

  startServer() {
    const { port, host } = config.http;
    
    this.httpServer.listen(port, host, () => {
      console.log(`🌐 Server running on http://${host}:${port}`);
      console.log(`📡 WebSocket server ready for connections`);
      console.log(`🎥 RTSP streaming server ready`);
      console.log('');
      console.log('Available endpoints:');
      console.log(`  - Health check: http://${host}:${port}/api/health`);
      console.log(`  - RTP Capabilities: http://${host}:${port}/api/rtp-capabilities`);
      console.log(`  - Start RTSP: POST http://${host}:${port}/api/rtsp/start`);
      console.log(`  - Stop RTSP: POST http://${host}:${port}/api/rtsp/stop`);
      console.log(`  - RTSP Status: http://${host}:${port}/api/rtsp/status`);
      console.log(`  - Stats: http://${host}:${port}/api/stats`);
    });

    // 优雅关闭
    this.setupGracefulShutdown();
    // 新增: 定时清理空闲流
    setInterval(() => {
      if (this.streamManager && typeof this.streamManager.cleanupIdleStreams === 'function') {
        this.streamManager.cleanupIdleStreams(5).catch(e => console.error('Idle stream cleanup error:', e));
      }
    }, 60 * 1000); // 每分钟检查一次
  }

  setupGracefulShutdown() {
    const shutdown = async (signal) => {
      console.log(`\n🛑 Received ${signal}, shutting down gracefully...`);
      
      try {
        // 停止 RTSP 流
        if (this.rtspHandler) {
          await this.rtspHandler.stopStream();
        }
        
        // 清理 MediaManager
        if (this.mediaManager) {
          await this.mediaManager.cleanup();
        }
        
        // 关闭 HTTP 服务器
        if (this.httpServer) {
          this.httpServer.close(() => {
            console.log('✅ Server shutdown completed');
            process.exit(0);
          });
        }
        
      } catch (error) {
        console.error('❌ Error during shutdown:', error);
        process.exit(1);
      }
    };

    process.on('SIGINT', () => shutdown('SIGINT'));
    process.on('SIGTERM', () => shutdown('SIGTERM'));
  }
}

// 启动服务器
const server = new MediasoupRTSPServer();
server.initialize().catch((error) => {
  console.error('Failed to start server:', error);
  process.exit(1);
});
